<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="权益编码" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入权益编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="权益名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入权益名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="权益供应方" prop="supplier">
        <el-select v-model="queryParams.supplier" placeholder="请选择权益供应方" clearable>
          <el-option v-for="dict in dict.type.interest_supplier" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="权益类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择权益类型" clearable>
          <el-option v-for="dict in dict.type.interest_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="领取方式" prop="payment">
        <el-select v-model="queryParams.payment" placeholder="请选择领取方式" clearable>
          <el-option v-for="dict in dict.type.interest_payment" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable v-model="queryParams.createTime" type="datetimerange" value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:interest:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['business:interest:edit']">修改</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:interest:remove']">删除</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="interestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="权益编码" align="center" prop="code" />
      <el-table-column label="权益名称" align="center" prop="name" />
      <el-table-column label="权益供应方" align="center" prop="supplier">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.interest_supplier" :value="scope.row.supplier" />
        </template>
      </el-table-column>
      <el-table-column label="权益类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.interest_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="领取方式" align="center" prop="payment">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.interest_payment" :value="scope.row.payment" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleView(scope.row)"
            v-hasPermi="['business:interest:query']">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:interest:edit']">修改</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:interest:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改权益管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="权益名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入权益名称" :disabled="viewType == 'view'" />
        </el-form-item>
        <el-form-item label="权益供应方" prop="supplier">
          <el-select v-model="form.supplier" placeholder="请选择权益供应方"
            :disabled="viewType == 'edit' || viewType == 'view'">
            <el-option v-for="dict in dict.type.interest_supplier" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权益类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择权益类型" :disabled="viewType == 'edit' || viewType == 'view'">
            <el-option v-for="dict in dict.type.interest_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权益领取方式" prop="payment">
          <el-select v-model="form.payment" placeholder="请选择领取方式" :disabled="viewType == 'edit' || viewType == 'view'">
            <el-option v-for="dict in dict.type.interest_payment" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="导入兑换码" v-if="viewType=='add'||viewType=='edit'">
          <el-button type="text" @click="downloadTemplate">下载导入模板</el-button>
          <el-upload ref="upload" action="#" :file-list="fileList" :on-change="onChange" :auto-upload="false"
            :multiple="false" :limit="1" style="margin-left:10px;display: inline;">
            <el-button slot="trigger" type="text">上传文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="兑换码发放有效期" prop="validType">
          <el-radio-group v-model="form.validType" :disabled="viewType == 'view'" @input="changeValidType">
            <el-radio v-for="dict in dict.type.coupon_valid_type" :key="dict.value"
              :label="dict.value">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="validValue" v-if="form.validType=='0'">
          <el-date-picker clearable v-model="form.validValue" type="datetime" placeholder="选择兑换截止日期"
            format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" :disabled="viewType == 'view'">
          </el-date-picker>
          <div>购买后在固定日期内可领取</div>
        </el-form-item>
        <el-form-item prop="validValue" v-if="form.validType == '1'">
          <el-input-number v-model="form.validValue" :min="0" :step="1" :precision="0"
            :disabled="viewType == 'view'"></el-input-number>
          <div>购买后N天内可领取</div>
        </el-form-item>
        <el-form-item label="券名称" prop="couponName">
          <el-input v-model="form.couponName" placeholder="请输入券名称" :disabled="viewType == 'view'" />
        </el-form-item>
        <el-form-item label="面额" prop="interestAmount">
          <el-input-number v-model="form.interestAmount" :min="0" :step="1" :precision="2"
            :disabled="viewType == 'view'"></el-input-number>
        </el-form-item>
        <el-form-item label="兑换链接" prop="url">
          <el-input v-model="form.url" placeholder="请输入兑换链接" :disabled="viewType == 'view'"></el-input>
        </el-form-item>
        <el-form-item label="券使用说明" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="viewType == 'view'" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInterest, getInterest, delInterest, addInterest, updateInterest, downloadCodeTemplate } from "@/api/business/interest";

export default {
  name: "Interest",
  dicts: ['interest_supplier', 'coupon_valid_type', 'interest_type', 'interest_payment'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 权益管理表格数据
      interestList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        supplier: null,
        type: null,
        payment: null,
        createTime: [],
        startTime: '',
        endTime:''
      },
      
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "权益编码不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "权益名称不能为空", trigger: "blur" }
        ],
        supplier: [
          { required: true, message: "权益供应方不能为空", trigger: "change" }
        ],
        type: [
          { required: true, message: "权益类型不能为空", trigger: "change" }
        ],
        payment: [
          { required: true, message: "领取方式不能为空", trigger: "change" }
        ],
        createtime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        validType: [
          { required: true, message: "兑换码发放有效期不能为空", trigger: "change" }
        ],
        validValue: [
          { required: true, message: "自定义日期不能为空", trigger: "change" }
        ],
        couponName: [
          { required: true, message: "券名称不能为空", trigger: "blur" }
        ],
        remark: [
          { required: true, message: "券使用说明不能为空", trigger: "blur" }
        ],
        url: [
          { required: true, message: "兑换链接不能为空", trigger: "blur" }
        ],
         interestAmount: [
          { required: true, message: "面额不能为空", trigger: "change" }
        ]
      },
      viewType:'',
      fileList:[],
      file:null
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询权益管理列表 */
    getList() {
      this.loading = true;
      if (this.queryParams.createTime.length>0){
        this.queryParams.startTime = this.queryParams.createTime[0];
        this.queryParams.endTime = this.queryParams.createTime[1];
      }
      this.$set(this.queryParams,'createTime','');
      listInterest(this.queryParams).then(response => {
        this.interestList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        supplier: null,
        type: null,
        payment: null,
        createtime: null,
        validType: '-1',
        validValue: null,
        couponName: null,
        remark: null,
        url:null,
        interestAmount:0
      };
      this.fileList=[];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.createTime = [];
      this.queryParams.startTime = '';
      this.queryParams.endTime = '';
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.viewType='add';
      this.title = "添加权益";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.viewType = 'edit';
      const id = row.id || this.ids
      getInterest(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改权益";
      });
    },
    handleView(row) {
      this.reset();
      this.viewType = 'view';
      const id = row.id || this.ids
      getInterest(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看权益";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let formData = new FormData();
          formData.append("file",this.file==null?null:this.file.raw);
          let keys = Object.keys(this.form);
          for(let key of keys){
            formData.append(key,this.form[key]);
          }
          if (this.form.id != null) {
            updateInterest(formData).then(response => {
              this.file=null;
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInterest(formData).then(response => {
              this.file = null;
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除权益管理编号为"' + ids + '"的数据项？').then(function() {
        return delInterest(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    changeValidType(){
      if(this.form.validType=='0'){
        this.form.validValue = new Date();
      } else if (this.form.validType == '1'){
        this.form.validValue = 1
      }
    },

    onChange(file,fileList){
      this.file =file;
    },
    /** 下载模板*/
    downloadTemplate(){
      this.download('/business/interest/downloadCodeTemplate', {
      }, `权益兑换码模板${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
